<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        show-icon
        :closable="false"
        title="注意，只允许为第三级分类设置相关参数！"
        type="warning"
      >
      </el-alert>

      <!--选择商品分类的区域  -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类</span>
          <!-- 选择商品分类的级联选择器 -->
          <el-cascader
            v-model="selectedCateId"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- 标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的页面 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="mini"
            @click="addDialogVisible = true"
          >
            添加参数
          </el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" stripe border>
            <!-- 展开列 -->
            <el-table-column type="expand" width="50">
              <template v-slot="{ row }">
                <el-tag
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteTag(row, i)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" width="50"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="openEditDialog(row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的页面 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="mini"
            @click="editDialogVisible = true"
          >
            添加属性
          </el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" stripe border>
            <!-- 展开列 -->
            <el-table-column type="expand" width="50">
              <template v-slot="{ row }">
                <!-- 循环渲染Tag标签 -->
                <el-tag
                  v-for="(item, i) in row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteTag(row, i)"
                >
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="row.inputVisible"
                  v-model="row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(row)"
                  @blur="handleInputConfirm(row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" width="50"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row }">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="openEditDialog(row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="`添加${titleText}`"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 表单区域 -->
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改属性对话框 -->
    <el-dialog
      :title="`修改${titleText}`"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <!-- 表单区域 -->
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="80px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      // 级联选择器配置
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器选中的id值
      selectedCateId: [],
      // 被激活的标签
      activeName: 'many',
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 显示或隐藏添加对话框
      addDialogVisible: false,
      // 添加参数的表单数据
      addForm: {
        attr_name: ''
      },
      // 表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改参数的表单数据
      editForm: {},
      // 显示或隐藏修改对话框
      editDialogVisible: false,
      // 修改表单规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类数据失败')
      }
      // 获取成功
      this.cateList = res.data
    },
    // 监听级联选择器的变化
    handleChange() {
      this.getParamsData()
    },
    // 监听标签页的变化
    handleTabClick() {
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData() {
      // 证明选中的是不是三级分类
      if (this.selectedCateId.length !== 3) {
        this.selectedCateId = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 证明选中的是三级分类
      const { data: res } = await this.$http.get(
        `categories/${this.idCate}/attributes`,
        {
          params: {
            sel: this.activeName
          }
        }
      )
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      res.data.forEach(item => {
        // 先判断字符串是否为空，并拆分数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 控制文本框的显示或隐藏
        item.inputVisible = false
        // 文本框的输入值
        item.inputValue = ''
      })

      // 获取成功
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 对话框关闭后重置内容
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 提交添加属性参数
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 校验成功
        const { data: res } = await this.$http.post(
          `categories/${this.idCate}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('提交参数错误')
        }
        // 提交成功
        this.$message.success('提交参数成功')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    // 重置修改对话框的表单
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 打开修改参数对话框
    async openEditDialog(attrId) {
      // 显示对话框
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(
        `categories/${this.idCate}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类参数失败')
      }
      // 获取成功
      this.editForm = res.data
    },
    // 提交修改后的数据
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.put(
          `categories/${this.idCate}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
            attr_vals: this.editForm.attr_vals
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('提交失败')
        }
        // 提交成功
        this.$message.success('提交成功')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除参数
    deleteParams(row) {
      this.$confirm(`此操作将永久删除参数${row.attr_name}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.idCate}/attributes/${row.attr_id}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.getParamsData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 鼠标失去焦点 或 enter后触发
    handleInputConfirm(row) {
      // 判断输入的是否全是空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = row.inputValue.trim()
        row.inputVisible = false
        return
      }
      // 输入有内容，则进行其他操作
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 上传数据到服务器
      this.setArrtVals(row)
    },
    // 删除tag
    deleteTag(row, i) {
      row.attr_vals.splice(i, 1)
      this.setArrtVals(row)
    },
    // 对attr_id 的操作
    async setArrtVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.idCate}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('提交参数失败')
      }
      // 提交参数成功
      this.$message.success('提交参数成功')
    },
    // 点击按钮，打开input
    showInput(row) {
      row.inputVisible = true
      // 文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 判断按钮是否需要禁用
    isBtnDisabled() {
      if (this.selectedCateId.length !== 3) {
        return true
      }
      return false
    },
    // 获取选中三级分类的Id
    idCate() {
      // 如果选中的是三级分类
      if (this.selectedCateId.length === 3) {
        return this.selectedCateId[2]
      }
      // 如果选中的不是三级分类
      return null
    },
    // 表单标题
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-cascader {
  margin-left: 10px;
}
.el-table {
  margin-top: 10px;
}
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 100px;
}
</style>
